import { Injectable, OnModuleInit } from "@nestjs/common";
import { configuration } from "../../../../config/config";
import * as net from "node:net";

@Injectable()
export class MockTransportServerService implements OnModuleInit {
  server: net.Server;

  onModuleInit(): any {
    console.log("mock machine socket server start");
    this.start();
  }

  start() {
    // 创建 TCP 服务器
    this.server = net.createServer((socket) => {
      // 处理关闭事件
      socket.on("end", () => {
        console.log("Client disconnected");
      });
      socket.on("data", (data) => {
        console.log("server 收到data:", data.toString());
      });
      // 处理错误事件
      socket.on("error", (err) => {
        console.error("Socket error:", err);
      });
      const sendSignal = () => {
        socket.write("123");
        setTimeout(sendSignal, 500);
      };
      sendSignal();
    });

    // 服务器监听在指定端口
    const PORT = configuration.hardwareServer.hardware_port;
    this.server.listen(PORT, () => {
      console.log(`TCP server is running on port ${PORT}`);
    });
  }

  close() {
    this.server.close();
  }
}
